/*
 * Niiuzu
 * Copyright (C) 2011  Thierry Nowak
 * 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.niiuzu.server.util;

import java.util.Random;
import java.util.UUID;

/**
 * Classe utilitaire comprenant toutes les méthodes nécessaires à la génération
 * et l'encryptage de mots de passes.
 */
public final class PasswordUtil {

	private static final char[] CHARSET_PWD = "abcdefghjkmnpqrstuvwxyABCDEFGHJKMNPQRSTUVWXY3456789"
			.toCharArray();

	private static final String PASSWORD_SALT_SEPARATOR = "@";

	/**
	 * Construit une nouvelle instance de {@link PasswordUtil}.
	 */
	private PasswordUtil() {
	}

	/**
	 * Génère un mot de passe aléatoirement.
	 * 
	 * @param passwordLength
	 *            longueur du mot de passe souhaitée.
	 */
	public static String generatePassword(int passwordLength) {
		Random random = new Random();
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < passwordLength; ++i) {
			int randomizedCharsetIndex = random.nextInt(CHARSET_PWD.length);
			char randomizedCharacter = CHARSET_PWD[randomizedCharsetIndex];
			builder.append(randomizedCharacter);
		}
		return builder.toString();
	}

	/**
	 * Génération du salage (cryptographie) nécessaire à l'encodage d'un mot de
	 * passe.
	 */
	public static String generateSalt() {
		return UUID.randomUUID().toString();
	}

	/**
	 * Encode un mot de passe.
	 * 
	 * @param clearPassword
	 *            valeur du mot de passe en clair (connu de l'utilisateur).
	 * @param salt
	 *            salage (cryptographie).
	 * @return mot de passe dans un format codé.
	 */
	public static String encodePassword(String clearPassword, String salt) {
		StringBuilder builder = new StringBuilder();
		builder.append(clearPassword);
		builder.append(PASSWORD_SALT_SEPARATOR);
		builder.append(salt);

		String hash = HashUtil.hashSha1(builder.toString());

		return hash;
	}

}
